import {
  warehousePageApi,
  addWarehouseApi,
  editWarehouseApi,
  delWarehouseApi
} from '@/api/system/sys/warehouse'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { WarehouseModel } from '@/api/model/sys/warehouse-model'
import dayjs from 'dayjs'

type Props = {
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  warehouseModalShow: Ref<boolean>
  warehouseForm: Ref<Partial<WarehouseModel>>
  proTableInst: Ref<ProTableInst | null>
}

export const useWarehouseApi = ({
  handleType,
  handleTag,
  warehouseModalShow,
  warehouseForm,
  proTableInst
}: Props) => {
  const confirmLoading = ref(false)

  // 获取仓库列表
  const fetchWarehousePage = async (
    pageRequest: PageRequest,
    queryParams: WarehouseModel
  ) => {
    const res = await warehousePageApi({
      ...queryParams,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改仓库
  const fetchAddOrEditWarehouse = async () => {
    confirmLoading.value = true
    const fetch =
      handleType.value === 'add' ? addWarehouseApi : editWarehouseApi
    const data =
      handleType.value === 'add'
        ? {
            ...warehouseForm.value,
            createdDate: dayjs().format('YYYY-MM-DD')
          }
        : { ...warehouseForm.value }
    if (data.__displayValue__) delete data.__displayValue__
    const res = await fetch(data)
    if (res.code === '0000') {
      useMsg('success', handleTag.value + '成功')
      proTableInst.value?.reload()
      warehouseModalShow.value = false
    }
    confirmLoading.value = false
  }

  // 删除仓库
  const fetchDelWarehouse = async (id) => {
    const res = await delWarehouseApi({ id })
    if (res.code === '0000') {
      useMsg('success', '删除成功')
      proTableInst.value?.reload()
    }
  }

  return {
    fetchWarehousePage,
    fetchAddOrEditWarehouse,
    fetchDelWarehouse,
    confirmLoading
  }
}
